package com.ikas.ai.server.aop;

import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.system.model.User;
import com.ikas.ai.server.module.system.service.PermissionService;
import com.ikas.ai.server.module.system.service.UserService;
import com.ikas.ai.server.security.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;

@Component
@Aspect
@Slf4j
public class SpecialPermissionAop {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    @Pointcut("@annotation(com.ikas.ai.server.aop.SpecialPermission)")
    public void specialPermission() {
    }

    @Around("specialPermission()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = ((MethodSignature) pjp.getSignature());
        SpecialPermission specialPermission = signature.getMethod().getAnnotation(SpecialPermission.class);
        //该方法所需权限
        String[] value = specialPermission.value();
        if (value == null) {
            return pjp.proceed();
        }
        Long userId = UserContextHolder.getTokenUser().getUserId();
        User user = userService.getUserById(userId);
        //该用户具有权限
        Set<String> userPermissions = permissionService.getUserPermissions(user);
        if (!userPermissions.containsAll(Arrays.asList(value))) {
            throw new BusinessException("无对应特殊权限操作,请联系管理员！");
        }
        return pjp.proceed();
    }

}
